package com.cyzy.controller;


import com.cyzy.dto.Result;
import com.cyzy.pojo.TrainUser;
import com.cyzy.service.UserService;
import com.cyzy.utils.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/user")
public class UserController {

  @Autowired
  private UserService userService;

    public static Map<String,String> codeMap = new HashMap<>();

    @GetMapping("/getVcode")
    public byte[] getVcode(@RequestParam String key) {
        Captcha captcha = new Captcha();
        String code = captcha.getCode();
        codeMap.put(key, code);
        System.out.println(key + "----1231");
        BufferedImage image = captcha.getImage();
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //登录
  @PostMapping("/login")
  public Result login(String userAcc, String userPwd,@RequestParam String key, @RequestParam String code,HttpSession session) {
      String Vcode = codeMap.get(key);
      if(Vcode != null && Vcode.equalsIgnoreCase(code)) {
          TrainUser trainUsers =  userService.login(userAcc, userPwd);
          session.setAttribute("user", trainUsers);
          if (trainUsers != null) {

              return Result.ok().message("登录成功").data("data", trainUsers);
          }
          return Result.error().message("账号或密码错误").data("data", null);
      }
      return Result.error().message("验证码错误").data("data", null);
  }

  //注册
    @PostMapping("/reg")
    public Result register(TrainUser trainUser) {
        int i = userService.addUser(trainUser);
        if (i == 0) {
            return Result.error().message("注册失败").data("data", null);
        }
        return Result.ok().message("注册成功");
    }

    //修改用户信息
    @PutMapping("/update")
    public Result updateUser(@RequestBody TrainUser trainUser) {
      int i = userService.updateUser(trainUser);
      if (i == 0) {
          return Result.error().message("修改失败");
      }
      return Result.ok().message("修改成功").data("data", trainUser);
    }

}
